package com.qqtech.qquan.sys.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qqtech.admin.context.AdminPage;
import com.qqtech.core.common.util.JsonUtil;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.qquan.sys.model.SysFunction;
import com.qqtech.qquan.sys.model.SysFunctionQuery;
import com.qqtech.qquan.sys.model.SysFunctionVo;
import com.qqtech.qquan.sys.service.SysFunctionService;
import com.qqtech.qquan.user.model.UserAdmin;

@Controller
@RequestMapping(value = "/sys/function")
public class SysFunctionController extends BaseAdminController {
	@Resource
	private SysFunctionService sysFunctionService;
	
	/**
	 * 列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list() {
		return "/function/function-list";
	}

	/**
	 * 列表页面数据
	 * 
	 * @param userDomain
	 *            查询条件
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage doList(SysFunctionQuery sysFunction, HttpServletRequest request,
			HttpServletResponse response) {

		AdminPage adminPage = new AdminPage();
		Pageable pageKit = new PageKit(sysFunction.getPage(), new PageOrder(Direction.ASC, "id"));
		Page<SysFunction> page = sysFunctionService.queryPageList(sysFunction, pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(page.getNumberOfElements());
		return adminPage;
	}

	@RequestMapping(value = "/tree", method = RequestMethod.POST)
	@ResponseBody
	public Result tree(HttpServletRequest request, HttpServletResponse response) {

		String parentId = request.getParameter("id");
		SysFunctionQuery sysFunctionQuery = new SysFunctionQuery();
		if(StringUtil.isNotBlank(parentId)){
			sysFunctionQuery.setParentId(Integer.valueOf(parentId));
		}
		List<SysFunctionVo> list = sysFunctionService.queryListByParentId(sysFunctionQuery);
		List<Map<Object, Object>> tree = new ArrayList<Map<Object, Object>>();
		if (null != list) {
			for (int i = 0; i < list.size(); i++) {
				SysFunctionVo m = (SysFunctionVo) list.get(i);
				Map<Object, Object> node = new HashMap<Object, Object>();
				node.put("id", m.getId());
				node.put("text", m.getName());
				if (m.getType() == 1) {
					node.put("state", "closed");
					node.put("iconCls", "icon-folder");
				} else {
					node.put("state", "open");
					node.put("iconCls", "icon-star");
				}
				Map<String, Object> attributes = new HashMap<String, Object>();
				attributes.put("parentId", m.getParentId());
				attributes.put("type", m.getType());
				node.put("attributes", attributes);
				tree.add(node);
			}
		}
		String json = JsonUtil.toJson(tree);
		try {
			response.getWriter().print(json);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String add(@RequestParam(required = false) Integer parentId, HttpServletRequest request,
			HttpServletResponse response) {
		if (null != parentId) {
			SysFunction parent = sysFunctionService.getById(parentId);
			request.setAttribute("parent", parent);
		}
		return "/function/function-update";
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result doAdd(SysFunction function, HttpServletRequest request, HttpServletResponse response) {
		UserAdmin userAdmin = this.getLoginUser();
		Result ret = new Result();
		if (StringUtils.isBlank(function.getName())) {
			ret.addErr("请输入功能名称");
		}
		if (ret.checkForm()) {
			function.setCreatorId(userAdmin.getId());
			function.setOidx(sysFunctionService.getMaxOrderIdx() + 1);
			sysFunctionService.insert(function);
		}
		return ret;
	}

	@RequestMapping(value = "/update/{functionId}", method = RequestMethod.GET)
	public String update(@PathVariable Integer functionId, HttpServletRequest request, HttpServletResponse response) {
		SysFunction function = sysFunctionService.getById(functionId);
		request.setAttribute("function", function);
		if (null != function && null != function.getParentId()) {
			SysFunction parent = sysFunctionService.getById(function.getParentId());
			request.setAttribute("parent", parent);
		}
		return "/function/function-update";
	}

	@RequestMapping(value = "/update/{functionId}", method = RequestMethod.POST)
	@ResponseBody
	public Result doUpdate(@PathVariable Integer functionId, SysFunction param) {
		SysFunction function = sysFunctionService.getById(functionId);
		Result ret = new Result();
		if (function == null) {
			ret.addErr("功能不存在");
		} else {
			if (StringUtil.isBlank(function.getName())) {
				ret.addErr("请输入功能名称");
			}
		}
		if (ret.checkForm()) {
			function.setName(param.getName());
			function.setType(param.getType());
			function.setStatus(param.getStatus());
			function.setUrl(param.getUrl());
			function.setRemark(param.getRemark());
			sysFunctionService.updateById(function);
		}
		return ret;
	}

	/**
	 * 移动节点
	 * 
	 * @param targetId
	 *            目标节点id
	 * @param sourceId
	 *            源节点id
	 * @param point
	 *            操作类型 取值范围: append,top,bottom
	 */
	@RequestMapping(value = "/move", method = RequestMethod.POST)
	@ResponseBody
	public Result move(@RequestParam Integer targetId, @RequestParam Integer sourceId, @RequestParam String point) {
		Result ret = new Result();
		if (null == targetId || null == sourceId || null == point) {
			ret.addErr("参数不能为空");
		}
		if (ret.checkForm()) {
			int value = sysFunctionService.move(targetId, sourceId, point);
			if (value == 0) {
				ret.addErr("叶子节点不允许追加子节点");
			}
		}
		return ret;
	}
	
	@RequestMapping(value = "/delete/{functionId}", method = RequestMethod.POST)
	@ResponseBody
	public Result doDelete(@PathVariable Integer functionId) {
		SysFunction function = sysFunctionService.getById(functionId);
		Result ret = new Result();
		if (function == null) {
			ret.addErr("功能不存在");
		} else {
			sysFunctionService.deleteById(functionId); 
		}
		return ret;
	}
}
